package com.soos.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soos.dto.Result;
import com.soos.dto.UserDTO;
import com.soos.entity.Blog;
import com.soos.entity.Follow;
import com.soos.entity.User;
import com.soos.mapper.FollowMapper;
import com.soos.service.IBlogService;
import com.soos.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soos.service.IUserService;
import com.soos.utils.ScrollResult;
import com.soos.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.soos.utils.RedisConstants.FEED_KEY;
import static com.soos.utils.RedisConstants.FOLLOW_USER_KEY;
import static com.soos.utils.SystemConstants.SCROLL_PAGE_SIZE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;
    @Resource
    private IBlogService blogService;

    /**
     * 尝试去关注这个用户
     * @param followUserId 关注这个用户的id
     * @param isFollow 是否关注 -> 是关注还是取关
     * @return 返回成功 or 失败
     */
    @Override
    public Result tryFollow(Long followUserId, Boolean isFollow) {
        //1.isFollow=true 代表关注
        Long userId = UserHolder.getUser().getId();
        if(isFollow) {
            //当前用户要关注这个人
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            save(follow);
            //保存到redis的set集合中
            String key = FOLLOW_USER_KEY + userId;
            stringRedisTemplate.opsForSet().add(key,followUserId.toString());
        }else {
            //2.isFollow=false 代表取关
            //new QueryWrapper<>().eq("user_id",userId).eq("follow_user_id",followUserId)
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                              .eq("user_id", userId)
                              .eq("follow_user_id", followUserId));
            if(isSuccess) {
                String key = FOLLOW_USER_KEY + userId;
                stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 是否关注这个用户
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        String key = FOLLOW_USER_KEY + userId;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, followUserId.toString());
        return Result.ok(isMember);
    }

    /**
     * 实现共同关注功能
     * 基本实现步骤 :
     * 1.查询共同关注的set集合然后转成UserDTO进行返回给前端即可
     * @param followUserId
     * @return
     */
    @Override
    public Result commonFollows(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        String key1 = FOLLOW_USER_KEY + userId;
        String key2 = FOLLOW_USER_KEY + followUserId;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if(intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }

        List<User> users = userService.
                listByIds(intersect.stream()
                        .map(Long::valueOf)
                        .collect(Collectors.toList()));

        List<UserDTO> userDTOS = users.stream().
                map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}